import DataManager from "../DataManager";

const { ccclass, property } = cc._decorator;

export enum VideoStatus {
    END = 0,    //结束录屏
    START = 1,  //开始录屏
    PAUSE = 2,  //录屏暂停 
    RESUME = 3, //录屏继续
}

@ccclass
export default class ZJTD_SDK {

    protected static _instance: ZJTD_SDK = null;
    private _shareTime: number;
    private isShared: boolean = false;
    private isGroupShared: boolean = false;
    private _shareGroupCb: any = null;
    private _shareCb: any = null;
    private _shareFb: any = null;
    private _intersitialAd: any;
    InterstitialAdId: any;
    private _bannerAds: any = null;
    BannerIds: any = ["b3grg0ha26r5e69gnl"];
    private _rewardedVideoAd = null;
    WatchVAD: boolean = false;
    RewardedVideoAdId: any = ["1yokp6sf82k256nm0l"];
    private _VideoAdcb = null;
    private _VideoAdfb = null;
    private _systemInfo: any;
    closeTime: number;
    AudioCloseTime: number;
    private _isAndroid: any;
    state: number = 0;
    RecorderManager: any;
    videoPath: string = "";
    private _wxUserInfo: any;

    public static get Instance(): ZJTD_SDK {
        if (ZJTD_SDK._instance == null) {
            ZJTD_SDK._instance = new ZJTD_SDK();
        }
        return ZJTD_SDK._instance;
    }

    public data: any = null;
    public ShareTitle: string[] = [
        "据说好看的人到哪都是最高分",
        "快看，你是超不过我的！",
        "噗！我需要您的帮助",
        "@你，我已经超过了，快来和我决斗",
        "实力不允许我低调"
    ];
    public ShareId: string[] = ['通过 MP 系统审核的图片编号']; // 通过 MP 系统审核的图片编号



    init() {
        console.log('tt初始化');
        this.craetTTRecorder();
        this.createBannerAds();
        let sysInfo = window["tt"].getSystemInfoSync();
        this._systemInfo = sysInfo;
    }

    init2() {
    }

    shareAppMessage(i = 0, cb?, fb?) {
        console.log('shareAppMessage...');
        let self = this;
        this.isShared = true;
        this._shareCb = cb;
        this._shareFb = fb;
        window["tt"].shareAppMessage({
            title: "小白快冲",
            desc: this.ShareTitle[i],
            imageUrl: "",
            query: "id:" + DataManager.Instance.getPlayerId(),
            success() {
                console.log("分享成功");
                if (self._shareCb) {
                    self._shareCb();
                    self._shareCb = null;
                }
            },
            fail(e) {
                console.log("分享失败");
                if (self._shareFb) {
                    self._shareFb();
                    self._shareFb = null;
                }
            },
        });

        this.closeTime = this.getCurTime();
        this._shareTime = this.getCurTime();
    }

    showInterstitialAd() {
        if (!window["tt"]) {
            return;
        }
        if (!this._intersitialAd) {
            this.createInterstitialAd();
            return;
        }
        this._intersitialAd.show();
    }


    showRewardedVideoAd(index = 0, cb, fb) {
        var self = this;
        var id = 0;
        this.AudioCloseTime = new Date().getTime();
        //console.log("创建视频广告", index, id, this.RewardedVideoAdId, this.RewardedVideoAdId[id]);
        var videoAd = window["tt"].createRewardedVideoAd({
            adUnitId: self.RewardedVideoAdId[id]
        });
        videoAd.load();
        this._VideoAdcb = cb;
        this._VideoAdfb = fb;
        // 显示广告
        videoAd
            .show()
            .then(() => {
                console.log("广告显示成功");
                this.TTRecorderCheck(VideoStatus.PAUSE);
            })
            .catch(err => {
                console.log("广告组件出现问题", err);
                // 可以手动加载一次
                videoAd.load().then(() => {
                    this.TTRecorderCheck(2);
                    console.log("手动加载成功");
                    // 加载成功后需要再显示广告
                    return videoAd.show();
                });
            });
        videoAd.onClose(res => {
            console.log("点击关闭视频", res);
            this.TTRecorderCheck(VideoStatus.RESUME);
            if (res.isEnded) {
                // 给予奖励
                this.WatchVAD = true;
                if (this._VideoAdcb) this._VideoAdcb();
                DataManager.Instance.setVideoNum(1);
                this._VideoAdcb = null;
            }
            else {
                /*
                if (require('GameMgr').Instance().ApiType === 2) {
                    let curTime = new Date().getTime();
                    console.log("看视频时间：", curTime, self.AudioCloseTime);
                    if (curTime - self.AudioCloseTime >= 10000) {
                        require('GameMgr').Instance().ShowADrewords();
                        // 正常播放结束，可以下发游戏奖励
                        require('GameMgr').Instance().setDaily(2);
                    }
                    else {*/
                if (this._VideoAdfb) this._VideoAdfb();
                this._VideoAdfb = null;
                return;
            }
        });

        if (!this._rewardedVideoAd) {
            return;
        }
    }



    showBannerAd(index) {
        index = 0;
        if (!window["tt"]) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        for (let i = 0; i < this._bannerAds.length; i++) {
            if (i != index) {
                this._bannerAds[i].hide();
            }
        }
        console.log(index)
        if (this._bannerAds[index]) {
            console.log("this._bannerAds", this._bannerAds[index])
            this._bannerAds[index].show();
            this._bannerAds[index].onLoad(() => {
                this._bannerAds[index]
                    .show()
                    .then(() => {
                        console.log("底部广告显示成功");
                    })
                    .catch(err => {
                        console.log("底部广告组件出现问题", err);
                    });
            });
        }
    }

    //隐藏所有广告
    hideBannerAds() {
        if (!window["tt"]) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        if (this._bannerAds && this._bannerAds.length != null) {
            if (this._bannerAds.length > 0) {
                for (var i = 0; i < this._bannerAds.length; i++) {
                    if (this._bannerAds && this._bannerAds[i]) {
                        this._bannerAds[i].hide();
                    }
                }
            }
        }
    }

    createBannerAds() {
        let winSize = this._systemInfo || window["tt"].getSystemInfoSync();; //window["tt"].getSystemInfoSync();
        let bannerHeight = 130;
        let bannerWidth = 300;
        console.log("廣告高度", (winSize.windowHeight - bannerHeight));

        this._bannerAds = [];
        var length = this.BannerIds.length;
        var self = this;
        for (let i = 0; i < length; i++) {
            var targetBannerAdWidth = 200;
            let banner = window["tt"].createBannerAd({
                adUnitId: self.BannerIds[i],
                adIntervals: 30,
                style: {
                    left: (winSize.windowWidth - bannerWidth) / 2,
                    top: winSize.windowHeight - (bannerHeight / 16) * 9 - 40,// 根据系统约定尺寸计算出广告高度
                    width: bannerWidth,
                }
            });
            //banner.style.left = (windowWidth - targetBannerAdWidth) / 2;
            banner.onError(function (res) {
                console.log('banner, ', res);
            });
            this._bannerAds[i] = banner;
        }
    }

    createInterstitialAd() {
        let self = this;

        if (this._intersitialAd) {
            return;
        }
        const isToutiaio = window["tt"].getSystemInfoSync().appName === "Toutiao";
        if (!this._isAndroid) {
            return;
        }
        // 插屏广告仅今日头条安卓客户端支持
        if (isToutiaio) {
            const interstitialAd = window["tt"].createInterstitialAd({
                adUnitId: this.InterstitialAdId
            });
            interstitialAd
                .load()
                .then(() => {
                    interstitialAd.show();
                })
                .catch(err => {
                    console.log(err);
                });
        }
    }

    craetTTRecorder() {
        this.state = 0;
        console.log('创建录屏');
        this.RecorderManager = window["tt"].getGameRecorderManager();
        if (!this.RecorderManager || !this.RecorderManager["start"]) return;
        //录屏开始
        this.RecorderManager.onStart((res) => {
            console.log('录屏开始');
            this.state = VideoStatus.START;
        });
        this.RecorderManager.onStop((res) => {
            let self = this;
            // if (this.RecorderManager["_duration"] && this.RecorderManager._duration >= 30) {
            //     this.RecorderManager.clipVideo({
            //         path: res.videoPath,
            //         timeRange: [10, 0],
            //         success(res1) {
            //             console.log(res1.videoPath); // 生成最后10秒的视频
            //             console.log('录屏结束');
            //             if (res1.videoPath) self.videoPath = res1.videoPath;
            //             if (self.videoPath) {
            //             }
            //             self.state = 0;
            //         },
            //         fail(e) {
            //             console.error(e);
            //             console.log(res.videoPath);
            //             console.log('录屏结束');
            //             self.state = 0;
            //         },
            //     });
            //     return;
            // }
            // else {
            this.state = VideoStatus.END;
            //}
            console.log(res.videoPath);
            console.log('录屏结束');
            this.videoPath = res.videoPath;
            if (this.videoPath) {
            }
        });
        this.RecorderManager.onInterruptionEnd(() => {
            this.TTRecorderCheck(VideoStatus.PAUSE);
            console.log('录屏中断暂停');
        })
        this.RecorderManager.onInterruptionBegin(() => {
            this.TTRecorderCheck(VideoStatus.RESUME);
            console.log('录屏中断继续');
        })
        this.RecorderManager.onPause(() => {
            this.state = VideoStatus.PAUSE;
            console.log('录屏暂停');
        })
        this.RecorderManager.onResume(() => {
            this.state = 1;
            console.log('录屏继续');
        })
    }

    getVideoState() {
        return this.videoPath;
    }
    getVideoTime() {
        return this.RecorderManager._duration;
    }

    TTShareVideo(cb?) {
        if (!this.videoPath) {
            this.showToast("录制视频失败");
            if (cb) cb("faile");
            return;
        }
        window["tt"].shareAppMessage({
            channel: "video",
            title: "分享视频",
            desc: "分享精彩一刻",
            imageUrl: "",
            templateId: "", // 替换成通过审核的分享ID
            query: "",
            extra: {
                videoPath: this.videoPath, // 可替换成录屏得到的视频地址
                videoTopics: ["录屏分享", "小游戏"]
            },
            success() {
                console.log("分享视频成功");
                if (cb) cb(true);
            },
            fail(e) {
                console.log("分享视频失败", e);
                if (e.errMsg == "shareAppMessage:cancel") {
                    // "分享视频失败,录制时间过短"
                    if (cb) cb(false);
                    this.showToast("取消分享");
                }
                else {
                    if (cb) cb("faile");
                }
            }
        });
    }

    showToast(msg: string, state = "fail") {
        return;
        if (!window["tt"]) return;
        window["tt"].showToast({
            title: msg,
            duration: 2000,
            icon: state,
            success(res) {
                console.log(`${res}`);
            },
            fail(res) {
                console.log(`showToast 调用失败`);
            },
        });
    }

    TTRecorderCheck(state = VideoStatus.END) {
        console.log('录屏----', state, this.state);
        console.log(this.RecorderManager);
        if (!this.RecorderManager || !this.RecorderManager["start"]) return;
        if (this.state != VideoStatus.END && state == VideoStatus.END) {
            console.log('录屏结束----');
            this.RecorderManager.stop();
        }
        else if (this.state == VideoStatus.END && state == VideoStatus.START) {
            console.log('录屏开始---');
            this.RecorderManager.start({
                duration: 30,
            })
        }
        else if (this.state == VideoStatus.START && state == VideoStatus.PAUSE) {
            console.log('录屏暂停---');
            this.RecorderManager.pause();
        }
        else if (this.state == VideoStatus.PAUSE && state == VideoStatus.RESUME) {
            console.log('录屏继续---');
            this.RecorderManager.resume()
        }
    }

    PYQshow() {
        window["tt"].hideShareMenu();
    }

    PYQhid() {
        window["tt"].hideShareMenu();
    }


    postDataToWX(score, now) {
        //向微信保存最高分数
        var kvDateList = new Array();
        kvDateList.push({
            key: "score",
            value: score + "",
        });
        kvDateList.push({
            key: "now",
            value: now + "",
        });
        console.log("托管游戏数据")
        console.log(kvDateList)
        //托管游戏数据
        //@ts-ignore
        window["tt"].setUserCloudStorage({
            KVDataList: kvDateList,
            success: (res) => {
                console.log("托管游戏数据tt.setUserCloudStorage success");
                console.log(res);
            },
            fail: (res) => {
                console.log("托管游戏数据tt.setUserCloudStorage fail");
                console.log(res);
            }
        });
    }

    setLogin(cb?) {
        if (!window["tt"]) {
            return;
        }
        let self = this;

        window["tt"].login({
            success(res) {
                console.log('字节跳动请求登录');
                console.log(res)
                if (res.code) {
                    console.log('字节跳动登录成功！')
                    console.log(res)
                    //发起网络请求
                    if (cb) cb(res);
                } else {
                    setTimeout(() => {
                        self.setLogin(cb);
                    }, 500);
                    console.log('登录失败！' + res.errMsg)
                }
            },
            complete() {
                console.log('登录调用完成');
            },
            fail(err) {
                console.log(err);
                console.log('再次登录');
                setTimeout(() => {
                    self.setLogin(cb);
                }, 500);
            }
        })
    }

    /**
     * 获取微信信息
     */
    getWeiXinInfo(cb?) {
        let self = this;

        window["tt"].showShareMenu({
        });

        window["tt"].onShareAppMessage(function (res) {
            //当监听到用户点击了分享或者拍抖音等按钮后，会执行该函数
            console.log(res.channel);
            // do something
            return {
                //执行函数后，这里是需要该函数返回的对象
                title: "小白快冲",
                // imageUrl: "https://example.com/test.png",

                desc: this.ShareTitle[0],
                query: "",
                success() {
                    console.log("分享成功");
                    if (self._shareCb) {
                        self._shareCb();
                        self._shareCb = null;
                    }
                },
                fail(e) {
                    console.log("分享失败");
                    if (self._shareFb) {
                        self._shareFb();
                        self._shareFb = null;
                    }
                }
            }; //返回的对象会传入tt.shareAppMessage进行最终分享
        });

        window["tt"].onShow((para) => {
            //console.log('onShow...' + JSON.stringify(para));
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本，res 是一个 undefined
            console.log("this.WatchVAD", this.WatchVAD);
            if (this.WatchVAD) {
                // 正常播放结束，可以下发游戏奖励
            }
        });

        window["tt"].onHide(function (para) {
            //console.log('onHide...' + JSON.stringify(para));
        });
        let sysInfo = window["tt"].getSystemInfoSync();

        this._systemInfo = sysInfo;

        self.setLogin((data) => {
            this.getSetting(cb, data);
        });
    }

    getSetting(cb, data?) {
        let self = this;
        window["tt"].getSetting({
            success(res) {
                console.log("用户授权1", res);
                if (res.authSetting["scope.userInfo"]) {
                    //console.log("用户已授权");
                    window["tt"].getUserInfo({
                        success(res1) {
                            //console.log(res);
                            //self._wxUserInfo = res.userInfo;
                            //此时可进行登录操作
                            // console.log('this._wxUserInfo=' + JSON.stringify(self._wxUserInfo));
                            console.log("用户授权：", res1);
                            console.log(res1);
                            // ZJTD_SDK.Instance.data = res;

                            // let sysInfo = window["tt"].getSystemInfoSync();
                            // self._systemInfo = sysInfo;
                            //self.setLogin(cb, res.data);
                            if (cb) cb(data, res1["userInfo"]);
                        }
                    });
                } else {
                    window["tt"].openSetting();
                    window["tt"].authorize({
                        scope: "scope.userInfo",
                        success(res2) {
                            console.log("scope.userInfo", res2);
                            // self._wxUserInfo = res.userInfo;
                            //此时可进行登录操作
                            // console.log('this._wxUserInfo=' + JSON.stringify(this._wxUserInfo));
                            console.log("用户授权：", res2);
                            console.log(res2);
                            //ZJTD_SDK.Instance.data = res;

                            //let sysInfo = window["tt"].getSystemInfoSync();
                            // self._systemInfo = sysInfo;
                            //self.setLogin(cb, res.data);
                            if (cb) cb(data, res2["userInfo"]);
                        }
                    });
                }
            }
        });
    }

    /**获取当前时间戳：秒 */
    getCurTime() {
        return Math.ceil(Date.now() / 1000);
    }

}
